package com.ruoyi.match.controller;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.match.domain.ChMarket;
import com.ruoyi.match.service.ChMarketService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.page.TableDataInfo;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * 股票信息Controller
 * 
 * @author ruoyi
 * @date 2023-12-20
 */
@RestController
@RequestMapping("/market")
public class ChMarketController extends BaseController {
    @Autowired
    private ChMarketService chMarketService;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 查询股票信息列表
     */
    @RequiresPermissions("match:market:list")
    @GetMapping("/list")
    public TableDataInfo list(ChMarket chMarket) throws IOException {
        startPage();
        SearchRequest searchRequest = new SearchRequest("stock_info");//索引名，就是表名
        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.requireFieldMatch(false);
        //高亮标签
        highlightBuilder.preTags("<font style='color:skyblue'>");
        highlightBuilder.postTags("</font>");
        SearchSourceBuilder searchSourceBuilder = null;
        if(StringUtils.isNotEmpty(chMarket.getName())){
            //构建搜索条件
            searchSourceBuilder = new SearchSourceBuilder()
                    .query(QueryBuilders.multiMatchQuery(chMarket.getName(), "name"))
                    .sort(SortBuilders.fieldSort("date").order(SortOrder.DESC))
                    .from(0)// 指定从哪条开始查询
                    .size(20)// 需要查出的总记录条数
                    .highlighter(highlightBuilder);//高亮
        }else {
            //构建搜索条件
            searchSourceBuilder = new SearchSourceBuilder()
                    .query(QueryBuilders.matchAllQuery())
                    .sort(SortBuilders.fieldSort("date").order(SortOrder.DESC))
                    .from(0)// 指定从哪条开始查询
                    .size(20)// 需要查出的总记录条数
                    .highlighter(highlightBuilder);//高亮
        }
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println("总条数："+searchResponse.getHits().getTotalHits());
        List<ChMarket> list = new LinkedList<>();
        for (org.elasticsearch.search.SearchHit hit : searchResponse.getHits().getHits()) {
            ChMarket stockInfo = JSONObject.parseObject(hit.getSourceAsString(), ChMarket.class);
            // 处理高亮显示的结果
            HighlightField contentField = hit.getHighlightFields().get("name");
            if (contentField != null) {
                stockInfo.setName(contentField.getFragments()[0].toString());
            }
            list.add(stockInfo);
        }
        return getDataTable(list);
    }
//    @RequiresPermissions("match:market:export")
//    @Log(title = "股票信息", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, ChMarket chMarket)
//    {
//        List<ChMarket> list = chMarketService.selectChMarketList(chMarket);
//        ExcelUtil<ChMarket> util = new ExcelUtil<ChMarket>(ChMarket.class);
//        util.exportExcel(response, list, "股票信息数据");
//    }
//
//    /**
//     * word导出
//     * @param response
//     * @param chMarket
//     */
//    @RequiresPermissions("match:market:export")
//    @Log(title = "股票信息", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, ChMarket chMarket) throws IOException {
//        List<ChMarket> list = chMarketService.selectChMarketList(chMarket);
//        XWPFDocument xwpfDocument = new XWPFDocument();
//        // 创建一个段落并设置内容
//        XWPFParagraph paragraph = xwpfDocument.createParagraph();
//        XWPFRun run = paragraph.createRun();
//        run.setText("日K数据详情数据表");
//        // 创建一个表格并设置表头
//        XWPFTable table = xwpfDocument.createTable(list.size() + 1, 3);
//        table.getRow(0).getCell(0).setText("日k股票代码");
//        table.getRow(0).getCell(1).setText("日k股票名称");
//        table.getRow(0).getCell(2).setText("日k股票价格");
//        // 填充表格数据
//        for (int i = 0; i < list.size(); i++) {
//            ChMarket market = list.get(i);
//            table.getRow(i+1).getCell(0).setText(market.getGid());
//            table.getRow(i+1).getCell(1).setText(market.getName());
//            table.getRow(i+1).getCell(2).setText(market.getTraAmount().toString());
//        }
//        // 设置响应头，告诉浏览器以附件形式下载 Word 文档
//        response.setHeader("Content-Disposition", "attachment; filename=\"stock_data.docx\"");
//        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
//        // 将文档写入响应流
//        ServletOutputStream outputStream = response.getOutputStream();
//        xwpfDocument.write(outputStream);
//        outputStream.close();
//    }
    /**
     * PDF导出
     * @param response
     * @param chMarket
     */
    @RequiresPermissions("match:market:export")
    @Log(title = "股票信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ChMarket chMarket) throws IOException {
        List<ChMarket> list = chMarketService.selectChMarketList(chMarket);
        PDDocument pdDocument = new PDDocument();
        // 通过字体文件路径加载字体
        PDType0Font load = PDType0Font.load(pdDocument, new File("E:\\ziti\\YiRenHuaKaiYiRenHuaLuo-2.ttf"));
        // 创建一页并设置页面尺寸
        PDPage pdPage = new PDPage(PDRectangle.A4);
        pdDocument.addPage(pdPage);
        // 创建一个内容流
        PDPageContentStream pdPageContentStream = new PDPageContentStream(pdDocument, pdPage);
        // 设置字体和字号
        pdPageContentStream.setFont(load,12);
        // 设置起始坐标
        float margin = 50;
        float yStart = pdPage.getMediaBox().getHeight() - margin;
        float tableWidth = pdPage.getMediaBox().getWidth() - 2 * margin;
        float yPosition = yStart;
        float tableHeight = 20f;
        float cellMargin = 5f;
        // 设置表头
        List<String> headers = Arrays.asList("日K股票代码", "日K股票名称", "日K股票价格");
        pdPageContentStream.beginText();
        pdPageContentStream.newLineAtOffset(margin,yPosition);
        for (String header : headers) {
            pdPageContentStream.showText(header);
            pdPageContentStream.newLineAtOffset(tableWidth/headers.size(),0);
        }
        pdPageContentStream.endText();
        // 填充表格数据
        pdPageContentStream.setFont(load,12);
        for (ChMarket market : list) {
            yPosition -= tableHeight;
            pdPageContentStream.beginText();
            pdPageContentStream.newLineAtOffset(margin,yPosition + cellMargin);
            pdPageContentStream.showText(market.getGid());
            pdPageContentStream.newLineAtOffset(tableWidth/headers.size(),0);
            pdPageContentStream.showText(market.getName());
            pdPageContentStream.newLineAtOffset(tableWidth/headers.size(),0);
            pdPageContentStream.showText(market.getTraAmount().toString());
            pdPageContentStream.endText();
        }
        // 关闭内容流
        pdPageContentStream.close();
        // 设置响应头，告诉浏览器以附件形式下载 PDF 文档
        response.setHeader("Content-Disposition", "attachment; filename=\"ch_market.pdf\"");
        response.setContentType("application/pdf");
        // 将文档写入响应流
        ServletOutputStream outputStream = response.getOutputStream();
        pdDocument.save(outputStream);
        // 关闭文档
        outputStream.close();
        pdDocument.close();
    }
}
